<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '900px' : '900px'"
    draggable
    @close="closeDialog"
  >
    <el-descriptions class="margin-top" title="" :column="3" border>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备编码</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.assetCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.assetName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备位置</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          <!-- {{ filterTypeName(formData.sopTypeId) }} -->
          {{ formData.locationName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">点检时间</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{
            formData.workTime
              ? dayjs(formData.workTime).format("YYYY-MM-DD")
              : ""
          }}
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">点检结果</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          <!-- {{ formData.checkResult }} -->

          <span :style="formData.checkResult == 0 ? 'color:red' : ''">{{
            formData.checkResult == 0 ? "异常" : "正常"
          }}</span>
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">点检标准</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.sopStandardName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">点检班组</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.executeTeamName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">点检人员</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.executePersonName }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-radio-group
      v-model="hh"
      @change="handleRadioChange"
      style="margin-top: 10px"
    >
      <el-radio-button label="全部" value="2" />
      <el-radio-button label="异常" value="0" />
    </el-radio-group>
    <el-table
      :data="inspectionList"
      style="width: 100%"
      :key="Math.random"
      show-overflow-tooltip
      max-height="300px"
      border
    >
      <el-table-column label="点检项" props="sopItemName" min-width="100">
        <template #default="{ $index, row }">
          <span>{{ row.sopItemName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点检方法" props="sopItemMethod" min-width="150">
        <template #default="{ $index, row }">
          <span>{{ row.sopItem.sopItemMethod }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点检工具" props="sopItemTool" min-width="150">
        <template #default="{ $index, row }">
          <span>{{ row.sopItem.sopItemTool }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点检记录" props="sopItemValue" min-width="150">
        <template #default="{ $index, row }">
          <span>{{ row.sopItemValue }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="点检结果"
        props="sopItemResult"
        min-width="150"
        align="center"
      >
        <template #default="{ $index, row }">
          <span :style="row.sopItemResult == 0 ? 'color:red' : ''">{{
            row.sopItemResult == 0 ? "异常" : "正常"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="标准值"
        props="sopItemStandard"
        min-width="220"
        align="center"
      >
        <template #default="{ $index, row }">
          <span>{{ row.sopItemStandard }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        props="images"
        min-width="220"
        align="center"
      >
        <template #default="{ $index, row }">
          <span v-for="(item, index) in row.images" :key="index">
            <img
              :src="`${upPreviewUrl}${item.url}`"
              style="
                width: 30px;
                height: 30px;
                margin-right: 10px;
                cursor: pointer;
              "
              @click="handlePictureCardPreview(`${upPreviewUrl}${item.url}`)"
              alt=""
            />
          </span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="巡检标准" props="sopStandardId" min-width="150">
          <template #default="{ $index, row }">
            <span>{{ row.sopStandardId }}</span>
          </template>
        </el-table-column> -->
    </el-table>
    <!-- <el-pagination
      small
      :background="true"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :total="inspectionList.length"
      layout="total, sizes, prev, pager, next, jumper"
      class="mt-[20px]"
      @size-change="handleEquSizeChange"
      @current-change="handleEquCurrentChange"
    /> -->
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        > -->
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useRouter } from "vue-router";
const dictionaryStore = useDictStoreHook();
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import dayjs from "dayjs";
const router = useRouter();

defineOptions({
  name: "EAMEQUINSPECTIONRECORDEDIT",
  inheritAttrs: false,
});
const defaultProps = {
  children: "children",
  label: "locationName",
};
const handleNodeClick = (data: Tree) => {
  if (data.id == "quanbu") {
    searchParam.value.inspectionTaskld = formData.id;
    searchParam.value.locationld = "";
    getTableList();
  } else {
    searchParam.value.inspectionTaskld = formData.id;
    searchParam.value.locationld = data.id;
    getTableList();
  }
};

const hh = ref("全部");

const handleRadioChange = (e) => {
  console.log(e);
  if (e == "全部") {
    currentPage.value = 1;
    pageSize.value = 5;
    inspectionList.value = oldInspectionList.value;
  } else if (e == "异常") {
    currentPage.value = 1;
    pageSize.value = 5;
    inspectionList.value = inspectionList.value.filter((item) => {
      return item.sopItemResult == "0";
    });
    console.log(formData.details);
  }
};

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

// 前端分页
const currentPage = ref(1);
const pageSize = ref(5);

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return inspectionList.value.slice(start, end);
});
const handleEquSizeChange = (newSize: number) => {
  pageSize.value = newSize;
};
const handleEquCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

// 请求参数
const requestApi = "/eam/equRouteInspectionOrder/queryByTask";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  inspectionTaskld: "",
  locationld: "",
};

const deleteParam = {
  api: "/qms/qmsexceptionsubtype/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// // 请求参数
// const equRequestApi = "/eam/equInspectionTask/queryByPage";

// // 是否需要分页
// const equPagination = true;

// const equInitParam = {};

// // 初始化搜索参数数据
// const equSearchParamInit = {
//   inspectionPlanld: "",
//   executeTeamld: "",
//   taskNo: "",
//   taskStatus: "",
//   inspectionStartDate: "",
//   inspectionEndDate: "",
//   inspectionDateSearch: [],
// };

// const equDeleteParam = {
//   api: "/qms/qmsexceptionsubtype/delete",
//   data: {},
// };

// // 数据请求错误后处理
// function equRequestError() {}

// const equDataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// let equTable = useTable(
//   equRequestApi,
//   equInitParam,
//   equSearchParamInit,
//   equPagination,
//   equDataCallBack.value,
//   equRequestError,
//   equDeleteParam
// );

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
const treeRef = ref();
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    // setTimeout(() => {
    //   formRef.value.clearValidate();
    // }, 50);
  }
);

const rules = reactive({
  exceptionTypeCode: [
    { required: true, message: "请选择分类问题", trigger: "change" },
  ],

  exceptionTypeSubCode: [
    { required: true, message: "请输入二级分类编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  exceptionTypeSubName: [
    { required: true, message: "请输入二级分类名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  assetKind: "",
  assetCode: "",
  assetName: "",
  locationName: "",
  createdUserId: "",
  createdUserName: "",
  endExecuteTime: "",
  exceptionNumber: "",
  executePersonId: "",
  executePersonName: "",
  executeTeamName: "",
  id: "",
  ids: "",
  inspectTotalNumber: "",
  inspectionPlanId: "",
  inspectionRouteId: "",
  inspectionRouteName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "1",
  lastUpdatedUserName: "",
  notInspectedNumber: "",
  organizationId: "",
  planExecuteTime: "",
  responseTime: "",
  routeLocationList: [],
  sopTypeId: "",
  startExecuteTime: "",
  taskName: "",
  taskNo: "",
  taskStatus: "",
  version: "",
  details: [],
  planTime: "",
  checkResult: "",
  workTime: "",
  sopStandardName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        assetKind,
        createTime,
        createdUserId,
        createdUserName,
        endExecuteTime,
        exceptionNumber,
        executePersonId,
        executePersonName,
        executeTeamName,
        id,
        ids,
        inspectTotalNumber,
        inspectionPlanId,
        inspectionRouteId,
        inspectionRouteName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        notInspectedNumber,
        organizationId,
        planExecuteTime,
        responseTime,
        routeLocationList,
        sopTypeId,
        startExecuteTime,
        taskName,
        taskNo,
        taskStatus,
        version,
        assetCode,
        assetName,
        locationName,
        checkResult,
        details,
        planTime,
        workTime,
        sopStandardName,
      } = newVal;
      Object.assign(formData, {
        assetKind,
        createTime,
        createdUserId,
        createdUserName,
        endExecuteTime,
        exceptionNumber,
        executePersonId,
        executePersonName,
        executeTeamName,
        id,
        ids,
        inspectTotalNumber,
        inspectionPlanId,
        inspectionRouteId,
        inspectionRouteName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        notInspectedNumber,
        organizationId,
        planExecuteTime,
        responseTime,
        routeLocationList,
        sopTypeId,
        startExecuteTime,
        taskName,
        taskNo,
        taskStatus,
        version,
        assetCode,
        assetName,
        locationName,
        checkResult,
        details,
        planTime,
        workTime,
        sopStandardName,
      });
      oldInspectionList.value = newVal.details;
      inspectionList.value = newVal.details;
      console.log(oldInspectionList.value);
      searchParam.value.inspectionTaskld = formData.id;
      searchParam.value.locationld = "";
      // getTableList();
      // 下一次更新选中路线全部
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formData.assetKind = "";

  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.endExecuteTime = "";
  formData.exceptionNumber = "";
  formData.executePersonId = "";
  formData.executePersonName = "";
  formData.executeTeamName = "";
  formData.id = "";
  formData.ids = "";
  formData.inspectTotalNumber = "";
  formData.inspectionPlanId = "";
  formData.inspectionRouteId = "";
  formData.inspectionRouteName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.notInspectedNumber = "";
  formData.organizationId = "";
  formData.planExecuteTime = "";
  formData.responseTime = "";
  formData.routeLocationList = [];
  formData.sopTypeId = "";
  formData.startExecuteTime = "";
  formData.taskName = "";
  formData.taskNo = "";
  formData.taskStatus = "";
  formData.version = "";

  formData.assetCode = "";
  formData.assetName = "";
  formData.locationName = "";
  formData.checkResult = "";
  formData.details = [];
  formData.planTime = "";
  formData.workTime = "";
  formData.sopStandardName = "";

  equList.value = [];
  inspectionList.value = [];
  oldInspectionList.value = [];
  hh.value = "全部";
}

// const loading = ref(false);

/** 问题二级分类保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmsexceptionsubtype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 巡检类型
const sopTypeList = ref([]);
const getSopTypeList = async () => {
  await request({
    url: "/eam/eamsoptype/getList",
    method: "post",
    data: {},
  }).then((res) => {
    sopTypeList.value = res.data;
    console.log(" sopTypeList.value", sopTypeList.value);
  });
};

// 产看计划（跳转）
const handlePLanClick = () => {
  console.log("跳转");
  router.push({
    path: "/eam/equ/eaminspectionplan",
  });
};

// 获取设备列表
const equList = ref([]);
const getEquList = async (inspectionTaskld: "", locationld: "") => {
  await request({
    url: "/eam/equRouteinspectionOrder/queryMylist",
    method: "post",
    data: { inspectionTaskld: inspectionTaskld, locationld: locationld },
  }).then((res) => {
    equList.value = res.data;
    console.log(" equList.value", equList.value);
  });
};

// 选中设备列表
const handleEquSelectionChange = (e) => {
  if (e) {
    getInspectionList(e.id, e.sopStandardId);
  }
};

//获取巡检列表
const oldInspectionList = ref([]);
const inspectionList = ref([]);
const getInspectionList = async (id, sopStandardId) => {
  await request({
    url: "/eam/eampointcheckorder/getDetails",
    method: "post",
    data: { id: id, sopStandardId: sopStandardId },
  }).then((res) => {
    inspectionList.value = res.data;
    oldInspectionList.value = res.data;
    console.log(" inspectionList.value", inspectionList.value);
  });
};

onMounted(() => {
  getSopTypeList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 120px;
}
</style>
